package cool.houge.wuneng.admin.controller;

import cool.houge.wuneng.admin.internal.VoBeanMapper;
import cool.houge.wuneng.admin.oas.model.UpdateMePasswordRequest;
import cool.houge.wuneng.admin.oas.model.UpdateMeProfileRequest;
import cool.houge.wuneng.admin.system.service.EmployeeService;
import cool.houge.wuneng.common.web.WebSupport;
import io.helidon.webserver.http.HttpRules;
import io.helidon.webserver.http.HttpService;
import io.helidon.webserver.http.ServerRequest;
import io.helidon.webserver.http.ServerResponse;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;

import static io.helidon.http.Status.NO_CONTENT_204;
import static io.helidon.webserver.http.SecureHandler.authenticate;

/// 个人信息
///
/// @author ZY (kzou227@qq.com)
@Singleton
public class MeController implements HttpService, WebSupport {

    @Inject
    VoBeanMapper beanMapper;

    @Inject
    EmployeeService employeeService;

    @Override
    public void routing(HttpRules rules) {
        rules.get("/me/profile", authenticate().wrap(this::getMeProfile));
        rules.put("/me/profile", authenticate().wrap(this::updateMeProfile));
        rules.put("/me/password", authenticate().wrap(this::updateMePassword));
    }

    void getMeProfile(ServerRequest req, ServerResponse res) {
        var dto = employeeService.getProfile(uid());
        dto.setRolePermits(authContext().rolePermits());

        var rs = beanMapper.toGetMeProfileResponse(dto);
        res.send(rs);
    }

    void updateMeProfile(ServerRequest req, ServerResponse res) {
        var vo = req.content().as(UpdateMeProfileRequest.class);
        validate(vo);

        var user = beanMapper.toEmployee(vo).setId(uid());
        employeeService.update(user);

        res.status(NO_CONTENT_204).send();
    }

    void updateMePassword(ServerRequest req, ServerResponse res) {
        var vo = req.content().as(UpdateMePasswordRequest.class);
        validate(vo);

        var entity = beanMapper.toEmployee(vo).setId(uid());
        employeeService.updatePassword(entity);

        res.status(NO_CONTENT_204).send();
    }
}
